package youcaihuaoa.weetop.com.vm.main

import android.app.Application
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.TextUtils
import androidx.databinding.ObservableField
import api.UserServiceFactory
import com.alibaba.fastjson.JSON
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.TimeUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.luck.picture.lib.entity.LocalMedia
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.configs.AppConstants
import com.robot.base.model.SignGroupBean
import com.robot.base.util.*
import com.robot.base.util.arouter.ARouterUtil
import com.robot.base.utils.ChoiceImgHelper
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.http.BaseResponse
import youcaihuaoa.weetop.com.GlApp
import youcaihuaoa.weetop.com.R
import youcaihuaoa.weetop.com.utils.BitmapUtils

class SignViewModel(application: Application) : GLBaseViewModel(application) {

    val workSign = ObservableField<Boolean>()

    val sleepSign = ObservableField<Boolean>()

    val workSignColor = ObservableField<Int>()

    val sleepSignColor = ObservableField<Int>()

    val workSignHintField = ObservableField<String>()

    val sleepSignHintField = ObservableField<String>()

    val workSignTimeShowField = ObservableField<String>()

    val sleepSignTimeShowField = ObservableField<String>()

    val cdCountField = ObservableField<String>()

    val ztCountField = ObservableField<String>()

    val kgCountField = ObservableField<String>()

    val signEnableField = ObservableField<Boolean>()

    var workSignTime = ""

    var workSignConfigTime = ""

    var sleepSignTime = ""

    var sleepSignConfigTime = ""

    var signProfile: SignGroupBean? = null

    val signVisibilityField = ObservableField<Boolean>(true)

    val clickToSignMapCommand = BindingCommand<Any>(BindingAction {
        if (signProfile?.kqz_data?.address_status == "1") {
            XXPermissions.with(ActivityUtils.getTopActivity())
                .permission(
                    Permission.ACCESS_COARSE_LOCATION,
                    Permission.ACCESS_FINE_LOCATION
                )
                // 申请多个权限
                // 设置不触发错误检测机制（局部设置）
                //.unchecked()
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>, all: Boolean) {
                        ARouterUtil.goToActivityWithBundle(AppConstants.Router.Main.A_SIGN_MAP,
                            Bundle().apply {
                                putString("signProfile", JSON.toJSONString(signProfile))
                            }
                        )
                    }

                    override fun onDenied(permissions: MutableList<String>, never: Boolean) {
                        ToastUtils.showShort("未取得位置权限!")
                    }
                })
        } else {
            if (signProfile?.kqz_data?.rl_status == "1") {
                doFace()
            } else {
                doSign()
            }
        }
    })


    fun fetchSignConfig(day: String) {
        val params =
            mapOf("day" to day)
        UserServiceFactory.attendanceGetGroup(params)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<SignGroupBean>>(this) {
                override fun onNext(t: BaseResponse<SignGroupBean>) {
                    signProfile = t.data
                    val sbdkData = signProfile?.sbdk_data
                    val xbdkData = signProfile?.xbdk_data
                    cdCountField.set(signProfile?.cd_num)
                    ztCountField.set(signProfile?.zt_num)
                    kgCountField.set(signProfile?.kg_num)
                    sleepSign.set(xbdkData != null)
                    workSign.set(sbdkData != null)
                    workSignConfigTime = signProfile?.kqz_data?.sbdk_time ?: ""
                    sleepSignConfigTime = signProfile?.kqz_data?.xbdk_time ?: ""
                    if (workSign.get() == true) {
                        //有上班打卡数据
                        workSignTime = sbdkData?.times ?: ""
                        workSignHintField.set("已打卡: $workSignTime")
                        workSignColor.set(ColorUtils.getColor(R.color.app_color_2886ff))
//                        workSignTimeShowField.set("上班：${workSignTime}")
                    } else {
                        workSignColor.set(ColorUtils.getColor(R.color.app_color_d9))
                        workSignHintField.set("未打卡")
                    }
                    workSignTimeShowField.set("上班：${workSignConfigTime}")
                    sleepSignTimeShowField.set("下班：${sleepSignConfigTime}")
                    if (sleepSign.get() == true) {
                        sleepSignTime = xbdkData?.times ?: ""
                        //有上班打卡数据
                        sleepSignHintField.set("已打卡: $sleepSignTime")
                        sleepSignColor.set(ColorUtils.getColor(R.color.app_color_2886ff))
//                        sleepSignTimeShowField.set("下班：")
                    } else {
                        sleepSignHintField.set("未打卡")
                        sleepSignColor.set(ColorUtils.getColor(R.color.app_color_d9))

                    }
                    if (day == TimeUtils.millis2String(System.currentTimeMillis(), "yyyy-MM-dd")) {
                        signEnableField.set(sleepSign.get() == false || workSign.get() == false)
                        signVisibilityField.set(true)
                    } else {
                        signVisibilityField.set(false)
                        signEnableField.set(false)
                    }
                }

                override fun onError(e: Throwable) {
                    super.onError(e)
                    signVisibilityField.set(false)
                }
            })
    }

    fun doFace() {
        ChoiceImgHelper.ChoiceOpenCamera(
            ActivityUtils.getTopActivity(),
            false,
            { result: List<LocalMedia?> ->
                val path = result[0]?.compressPath ?: ""
                GlApp.getContext()?.let {
                    Glide.with(it)
                        .asBitmap()
                        .load(path)
                        .into(object : CustomTarget<Bitmap>() {
                            override fun onResourceReady(
                                resource: Bitmap,
                                transition: Transition<in Bitmap>?
                            ) {
                                doSign(BitmapUtils.bitmapToBase64(resource))
                            }

                            override fun onLoadCleared(placeholder: Drawable?) {

                            }

                        })
                }
            },
            {})
    }


    fun doSign() {
        val wifiStatus = signProfile?.kqz_data?.wifi_status ?: "0"//wifi验证
        val addressStatus = signProfile?.kqz_data?.address_status ?: "0"//地址验证
        val params = mutableMapOf("group_id" to signProfile?.kqz_data?.id)

        if (wifiStatus == "1") {
            //wifi验证
            val wifiMacAddress = WifiMacUtil.getBBSid(GlApp.getContext())
            if (TextUtils.isEmpty(wifiMacAddress)) {
                ToastUtils.showShort("不存在wifi")
                return
            }
            params["wifi_mac"] = wifiMacAddress
        }
        if (addressStatus == "1") {
            params["address_data"] = ""
            params["address_lng"] = ""
            params["address_lat"] = ""
        }
        UserServiceFactory.userDk(params.toMap())
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<Any>>(this) {
                override fun onNext(t: BaseResponse<Any>) {
                    ToastUtils.showShort("打卡成功")
                    LiveDataBus.get().with("sign_success").postValue("")
                }
            })
    }

    fun doSign(base64: String) {
        val wifiStatus = signProfile?.kqz_data?.wifi_status ?: "0"//wifi验证
        val addressStatus = signProfile?.kqz_data?.address_status ?: "0"//地址验证
        val params = mutableMapOf("group_id" to signProfile?.kqz_data?.id)
        params["rl_image_path"] = base64
        LogUtils.d("base64----${base64}")
        if (wifiStatus == "1") {
            //wifi验证
            val wifiMacAddress = WifiMacUtil.getBBSid(GlApp.getContext())
            if (TextUtils.isEmpty(wifiMacAddress)) {
                ToastUtils.showShort("不存在wifi")
                return
            }
            params["wifi_mac"] = wifiMacAddress
            LogUtils.d("wifimac----${wifiMacAddress}")
        }
        if (addressStatus == "1") {
            params["address_data"] = ""
            params["address_lng"] = ""
            params["address_lat"] = ""
        }
        LogUtils.e("requestParams----${params}")

        UserServiceFactory.userDk(params.toMap())
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<Any>>(this) {
                override fun onNext(t: BaseResponse<Any>) {
                    ToastUtils.showShort("打卡成功")
                    LiveDataBus.get().with("sign_success").postValue("")
                }
            })
    }

}